// 贪吃蛇游戏主逻辑文件

// 游戏常量
const GRID_SIZE = 25;
const GRID_WIDTH = 20; // 500 / 25
const GRID_HEIGHT = 20; // 500 / 25
const INITIAL_SPEED = 150;

// 游戏变量
let canvas, ctx;
let snake = [];
let food = {};
let obstacles = [];
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let gameRunning = false;
let gamePaused = false;
let gameLoop;
let gameStats = {
    gamesPlayed: 0,
    highestScore: 0,
    achievements: {}
};
let achievements = {
    'first_kill': { name: '首杀', description: '吃掉第一个食物', unlocked: false },
    'speed_master': { name: '速度达人', description: '达到1000分', unlocked: false },
    'marathon': { name: '马拉松选手', description: '单局游戏蛇身长度达到30节', unlocked: false },
    'collector': { name: '收藏家', description: '累计获得5000分', unlocked: false },
    'easy_achiever': { name: '简单大师', description: '在简单难度下达到500分', unlocked: false },
    'medium_challenger': { name: '中等挑战者', description: '在中等难度下达到1000分', unlocked: false },
    'hard_master': { name: '困难大师', description: '在困难难度下达到1500分', unlocked: false },
    'obstacle_expert': { name: '障碍专家', description: '在困难难度下吃掉50个食物', unlocked: false },
    'survivor': { name: '生存专家', description: '在困难环境下生存2分钟', unlocked: false }
};
let difficulty = 1; // 1=简单, 2=中等, 3=困难
let audioEnabled = true;
let startTime;
let foodEaten = 0;

// DOM元素
let scoreDisplay, gamesPlayedDisplay, highestScoreDisplay, achievementsUnlockedDisplay;
let startButton, pauseButton, retryButton, achievementsButton, closeAchievementsButton;
let difficultySelect, audioToggle;
let messageDisplay, achievementsOverlay, achievementsDisplay;
let upKey, downKey, leftKey, rightKey;

// 音效
let eatSound, gameOverSound, achievementSound;

// 初始化游戏
function initGame() {
    // 获取Canvas元素
    canvas = document.getElementById('game-board');
    ctx = canvas.getContext('2d');
    
    // 获取DOM元素
    scoreDisplay = document.getElementById('score-display');
    gamesPlayedDisplay = document.getElementById('games-played');
    highestScoreDisplay = document.getElementById('highest-score');
    achievementsUnlockedDisplay = document.getElementById('achievements-unlocked');
    startButton = document.getElementById('start-button');
    pauseButton = document.getElementById('pause-button');
    retryButton = document.getElementById('retry-button');
    achievementsButton = document.getElementById('achievements-button');
    closeAchievementsButton = document.getElementById('close-achievements');
    difficultySelect = document.getElementById('difficulty-select');
    audioToggle = document.getElementById('audio-toggle');
    messageDisplay = document.getElementById('message-display');
    achievementsOverlay = document.getElementById('achievements-overlay');
    achievementsDisplay = document.getElementById('achievements-display');
    upKey = document.getElementById('up-key');
    downKey = document.getElementById('down-key');
    leftKey = document.getElementById('left-key');
    rightKey = document.getElementById('right-key');
    
    // 初始化音效
    initAudio();
    
    // 加载游戏统计数据
    loadGameStats();
    
    // 更新显示
    updateStatsDisplay();
    updateAchievementsDisplay();
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化游戏状态
    resetGame();
}

// 初始化音效
function initAudio() {
    // 创建简单的音效（使用Web Audio API）
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        // 吃食物音效
        eatSound = () => {
            if (!audioEnabled) return;
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            oscillator.type = 'sine';
            oscillator.frequency.value = 523.25; // C5
            gainNode.gain.value = 0.3;
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.1);
        };
        
        // 游戏结束音效
        gameOverSound = () => {
            if (!audioEnabled) return;
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            oscillator.type = 'sine';
            oscillator.frequency.value = 220; // A3
            gainNode.gain.value = 0.3;
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.5);
        };
        
        // 成就解锁音效
        achievementSound = () => {
            if (!audioEnabled) return;
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            oscillator.type = 'sine';
            
            // 播放一个简单的旋律
            const now = audioContext.currentTime;
            oscillator.frequency.setValueAtTime(523.25, now); // C5
            oscillator.frequency.setValueAtTime(659.25, now + 0.1); // E5
            oscillator.frequency.setValueAtTime(783.99, now + 0.2); // G5
            oscillator.frequency.setValueAtTime(1046.50, now + 0.3); // C6
            
            gainNode.gain.setValueAtTime(0.3, now);
            gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.5);
            
            oscillator.start(now);
            oscillator.stop(now + 0.5);
        };
    } catch (e) {
        console.log('Audio not supported');
        eatSound = () => {};
        gameOverSound = () => {};
        achievementSound = () => {};
    }
}

// 绑定事件监听器
function bindEventListeners() {
    // 游戏控制按钮
    startButton.addEventListener('click', startGame);
    pauseButton.addEventListener('click', togglePause);
    retryButton.addEventListener('click', resetGame);
    
    // 成就榜按钮
    achievementsButton.addEventListener('click', showAchievements);
    closeAchievementsButton.addEventListener('click', hideAchievements);
    
    // 设置控制
    difficultySelect.addEventListener('change', changeDifficulty);
    audioToggle.addEventListener('click', toggleAudio);
    
    // 键盘控制
    document.addEventListener('keydown', handleKeyDown);
    
    // 移动端控制
    if (upKey) upKey.addEventListener('click', () => changeDirection('up'));
    if (downKey) downKey.addEventListener('click', () => changeDirection('down'));
    if (leftKey) leftKey.addEventListener('click', () => changeDirection('left'));
    if (rightKey) rightKey.addEventListener('click', () => changeDirection('right'));
    
    // 点击成就遮罩层关闭
    achievementsOverlay.addEventListener('click', (e) => {
        if (e.target === achievementsOverlay) {
            hideAchievements();
        }
    });
}

// 键盘事件处理
function handleKeyDown(e) {
    switch(e.key) {
        case 'ArrowUp':
        case 'w':
        case 'W':
            changeDirection('up');
            break;
        case 'ArrowDown':
        case 's':
        case 'S':
            changeDirection('down');
            break;
        case 'ArrowLeft':
        case 'a':
        case 'A':
            changeDirection('left');
            break;
        case 'ArrowRight':
        case 'd':
        case 'D':
            changeDirection('right');
            break;
        case 'p':
        case 'P':
            togglePause();
            break;
    }
}

// 改变方向
function changeDirection(newDirection) {
    // 防止反向移动
    if (
        (newDirection === 'up' && direction !== 'down') ||
        (newDirection === 'down' && direction !== 'up') ||
        (newDirection === 'left' && direction !== 'right') ||
        (newDirection === 'right' && direction !== 'left')
    ) {
        nextDirection = newDirection;
    }
}

// 改变难度
function changeDifficulty() {
    difficulty = parseInt(difficultySelect.value);
    if (gameRunning) {
        resetGame();
        startGame();
    }
}

// 切换音效
function toggleAudio() {
    audioEnabled = !audioEnabled;
    audioToggle.textContent = audioEnabled ? '🔊 音效' : '🔇 音效';
}

// 显示成就榜
function showAchievements() {
    updateAchievementsDisplay();
    achievementsOverlay.style.display = 'flex';
}

// 隐藏成就榜
function hideAchievements() {
    achievementsOverlay.style.display = 'none';
}

// 更新成就显示
function updateAchievementsDisplay() {
    let unlockedCount = 0;
    let achievementsHTML = '';
    
    for (const [key, achievement] of Object.entries(achievements)) {
        if (achievement.unlocked) unlockedCount++;
        achievementsHTML += `
            <div class="achievement-item ${achievement.unlocked ? 'completed' : ''}">
                <div class="achievement-name">${achievement.name}</div>
                <div class="achievement-description">${achievement.description}</div>
                ${achievement.unlocked ? `<div class="achievement-timestamp">已解锁</div>` : ''}
            </div>
        `;
    }
    
    achievementsDisplay.innerHTML = achievementsHTML;
    achievementsUnlockedDisplay.textContent = `成就: ${unlockedCount}/${Object.keys(achievements).length}`;
}

// 开始游戏
function startGame() {
    if (gameRunning) return;
    
    gameRunning = true;
    gamePaused = false;
    startButton.style.display = 'none';
    pauseButton.style.display = 'inline-block';
    retryButton.style.display = 'none';
    messageDisplay.textContent = '';
    
    // 更新游戏统计数据
    gameStats.gamesPlayed++;
    updateStatsDisplay();
    
    // 记录开始时间
    startTime = new Date();
    
    // 重置食物计数
    foodEaten = 0;
    
    // 生成障碍物
    generateObstacles();
    
    // 开始游戏循环
    const speed = INITIAL_SPEED - (difficulty - 1) * 30;
    gameLoop = setInterval(update, speed);
}

// 切换暂停
function togglePause() {
    if (!gameRunning) return;
    
    gamePaused = !gamePaused;
    pauseButton.textContent = gamePaused ? '继续' : '暂停';
    
    if (gamePaused) {
        clearInterval(gameLoop);
        messageDisplay.textContent = '游戏暂停';
    } else {
        const speed = INITIAL_SPEED - (difficulty - 1) * 30;
        gameLoop = setInterval(update, speed);
        messageDisplay.textContent = '';
    }
}

// 重置游戏
function resetGame() {
    // 清除游戏循环
    if (gameLoop) {
        clearInterval(gameLoop);
    }
    
    // 重置游戏状态
    gameRunning = false;
    gamePaused = false;
    
    // 重置蛇
    snake = [
        {x: 10, y: 10}, // 头部
        {x: 9, y: 10},
        {x: 8, y: 10}  // 尾部
    ];
    
    // 设置初始方向
    direction = 'right';
    nextDirection = 'right';
    
    // 重置分数
    score = 0;
    scoreDisplay.textContent = `分数: ${score}`;
    
    // 生成食物
    generateFood();
    
    // 清空障碍物
    obstacles = [];
    
    // 重置UI
    startButton.style.display = 'inline-block';
    pauseButton.style.display = 'none';
    retryButton.style.display = 'none';
    pauseButton.textContent = '暂停';
    messageDisplay.textContent = '';
    
    // 绘制初始状态
    draw();
}

// 更新游戏状态
function update() {
    if (gamePaused) return;
    
    // 更新方向
    direction = nextDirection;
    
    // 移动蛇
    moveSnake();
    
    // 检查碰撞
    if (checkCollision()) {
        gameOver();
        return;
    }
    
    // 检查是否吃到食物
    checkFood();
    
    // 绘制游戏画面
    draw();
    
    // 检查成就
    checkAchievements();
}

// 移动蛇
function moveSnake() {
    // 创建新头部
    const head = {...snake[0]};
    
    // 根据方向移动头部
    switch(direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    // 将新头部添加到蛇身
    snake.unshift(head);
    
    // 移除尾部（除非吃到食物）
    snake.pop();
}

// 检查碰撞
function checkCollision() {
    const head = snake[0];
    
    // 检查边界碰撞
    if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT) {
        return true;
    }
    
    // 检查自身碰撞
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            return true;
        }
    }
    
    // 检查障碍物碰撞
    for (const obstacle of obstacles) {
        if (head.x === obstacle.x && head.y === obstacle.y) {
            return true;
        }
    }
    
    return false;
}

// 生成食物
function generateFood() {
    let newFood;
    let foodOnSnake;
    let foodOnObstacle;
    
    do {
        foodOnSnake = false;
        foodOnObstacle = false;
        newFood = {
            x: Math.floor(Math.random() * GRID_WIDTH),
            y: Math.floor(Math.random() * GRID_HEIGHT)
        };
        
        // 检查食物是否在蛇身上
        for (const segment of snake) {
            if (newFood.x === segment.x && newFood.y === segment.y) {
                foodOnSnake = true;
                break;
            }
        }
        
        // 检查食物是否在障碍物上
        for (const obstacle of obstacles) {
            if (newFood.x === obstacle.x && newFood.y === obstacle.y) {
                foodOnObstacle = true;
                break;
            }
        }
    } while (foodOnSnake || foodOnObstacle);
    
    food = newFood;
}

// 检查是否吃到食物
function checkFood() {
    const head = snake[0];
    
    if (head.x === food.x && head.y === food.y) {
        // 播放音效
        if (eatSound) eatSound();
        
        // 增加分数
        score += 10;
        scoreDisplay.textContent = `分数: ${score}`;
        
        // 增加食物计数
        foodEaten++;
        
        // 蛇身增长（不移除尾部）
        const tail = {...snake[snake.length - 1]};
        snake.push(tail);
        
        // 生成新食物
        generateFood();
    }
}

// 生成障碍物
function generateObstacles() {
    obstacles = [];
    
    // 根据难度生成障碍物
    let obstacleCount = 0;
    switch(difficulty) {
        case 1: // 简单 - 无障碍物
            obstacleCount = 0;
            break;
        case 2: // 中等 - 1个障碍物
            obstacleCount = 1;
            break;
        case 3: // 困难 - 5个障碍物
            obstacleCount = 5;
            break;
    }
    
    // 生成障碍物
    for (let i = 0; i < obstacleCount; i++) {
        let newObstacle;
        let obstacleOnSnake;
        let obstacleOnFood;
        let obstacleOnExisting;
        
        do {
            obstacleOnSnake = false;
            obstacleOnFood = false;
            obstacleOnExisting = false;
            newObstacle = {
                x: Math.floor(Math.random() * GRID_WIDTH),
                y: Math.floor(Math.random() * GRID_HEIGHT)
            };
            
            // 检查障碍物是否在蛇身上
            for (const segment of snake) {
                if (newObstacle.x === segment.x && newObstacle.y === segment.y) {
                    obstacleOnSnake = true;
                    break;
                }
            }
            
            // 检查障碍物是否在食物上
            if (newObstacle.x === food.x && newObstacle.y === food.y) {
                obstacleOnFood = true;
            }
            
            // 检查障碍物是否在已有障碍物上
            for (const obstacle of obstacles) {
                if (newObstacle.x === obstacle.x && newObstacle.y === obstacle.y) {
                    obstacleOnExisting = true;
                    break;
                }
            }
        } while (obstacleOnSnake || obstacleOnFood || obstacleOnExisting);
        
        obstacles.push(newObstacle);
    }
}

// 绘制游戏画面
function draw() {
    // 清空画布
    ctx.fillStyle = '#111';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格背景
    drawGrid();
    
    // 绘制蛇
    drawSnake();
    
    // 绘制食物
    drawFood();
    
    // 绘制障碍物
    drawObstacles();
}

// 绘制网格背景
function drawGrid() {
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)';
    ctx.lineWidth = 1;
    
    // 绘制垂直线
    for (let x = 0; x <= canvas.width; x += GRID_SIZE) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.height);
        ctx.stroke();
    }
    
    // 绘制水平线
    for (let y = 0; y <= canvas.height; y += GRID_SIZE) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(canvas.width, y);
        ctx.stroke();
    }
}

// 绘制蛇
function drawSnake() {
    // 绘制蛇身
    for (let i = 0; i < snake.length; i++) {
        const segment = snake[i];
        
        // 蛇身颜色渐变
        if (i === 0) {
            // 头部
            ctx.fillStyle = '#4CAF50';
        } else {
            // 身体
            const colorValue = Math.max(100, 200 - Math.floor(i / snake.length * 100));
            ctx.fillStyle = `rgb(50, ${colorValue}, 80)`;
        }
        
        // 绘制圆角矩形
        ctx.beginPath();
        ctx.roundRect(
            segment.x * GRID_SIZE, 
            segment.y * GRID_SIZE, 
            GRID_SIZE, 
            GRID_SIZE, 
            5
        );
        ctx.fill();
        
        // 绘制边框
        ctx.strokeStyle = '#2E7D32';
        ctx.lineWidth = 1;
        ctx.stroke();
        
        // 绘制眼睛（仅头部）
        if (i === 0) {
            ctx.fillStyle = '#000';
            const eyeSize = GRID_SIZE / 5;
            
            // 根据方向绘制眼睛
            switch(direction) {
                case 'right':
                    ctx.fillRect(
                        (segment.x + 0.7) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.3) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    ctx.fillRect(
                        (segment.x + 0.7) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.7) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    break;
                case 'left':
                    ctx.fillRect(
                        (segment.x + 0.3) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.3) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    ctx.fillRect(
                        (segment.x + 0.3) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.7) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    break;
                case 'up':
                    ctx.fillRect(
                        (segment.x + 0.3) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.3) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    ctx.fillRect(
                        (segment.x + 0.7) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.3) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    break;
                case 'down':
                    ctx.fillRect(
                        (segment.x + 0.3) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.7) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    ctx.fillRect(
                        (segment.x + 0.7) * GRID_SIZE - eyeSize/2,
                        (segment.y + 0.7) * GRID_SIZE - eyeSize/2,
                        eyeSize,
                        eyeSize
                    );
                    break;
            }
        }
    }
}

// 绘制食物
function drawFood() {
    // 绘制苹果
    ctx.fillStyle = '#F44336';
    ctx.beginPath();
    ctx.arc(
        food.x * GRID_SIZE + GRID_SIZE/2,
        food.y * GRID_SIZE + GRID_SIZE/2,
        GRID_SIZE/2 - 2,
        0,
        Math.PI * 2
    );
    ctx.fill();
    
    // 绘制高光
    ctx.fillStyle = '#FFCDD2';
    ctx.beginPath();
    ctx.arc(
        food.x * GRID_SIZE + GRID_SIZE/3,
        food.y * GRID_SIZE + GRID_SIZE/3,
        GRID_SIZE/6,
        0,
        Math.PI * 2
    );
    ctx.fill();
    
    // 绘制叶子
    ctx.fillStyle = '#4CAF50';
    ctx.beginPath();
    ctx.ellipse(
        food.x * GRID_SIZE + GRID_SIZE/1.5,
        food.y * GRID_SIZE + GRID_SIZE/4,
        GRID_SIZE/6,
        GRID_SIZE/3,
        Math.PI/4,
        0,
        Math.PI * 2
    );
    ctx.fill();
}

// 绘制障碍物
function drawObstacles() {
    for (const obstacle of obstacles) {
        // 绘制石头
        ctx.fillStyle = '#757575';
        ctx.beginPath();
        ctx.arc(
            obstacle.x * GRID_SIZE + GRID_SIZE/2,
            obstacle.y * GRID_SIZE + GRID_SIZE/2,
            GRID_SIZE/2 - 2,
            0,
            Math.PI * 2
        );
        ctx.fill();
        
        // 绘制纹理
        ctx.fillStyle = '#616161';
        for (let i = 0; i < 3; i++) {
            ctx.beginPath();
            ctx.arc(
                obstacle.x * GRID_SIZE + GRID_SIZE/2 + (Math.random() - 0.5) * GRID_SIZE/2,
                obstacle.y * GRID_SIZE + GRID_SIZE/2 + (Math.random() - 0.5) * GRID_SIZE/2,
                Math.random() * GRID_SIZE/8,
                0,
                Math.PI * 2
            );
            ctx.fill();
        }
    }
}

// 游戏结束
function gameOver() {
    // 清除游戏循环
    clearInterval(gameLoop);
    
    // 播放游戏结束音效
    if (gameOverSound) gameOverSound();
    
    // 更新游戏状态
    gameRunning = false;
    gamePaused = false;
    
    // 显示游戏结束消息
    messageDisplay.textContent = '游戏结束!';
    
    // 显示重试按钮
    retryButton.style.display = 'inline-block';
    pauseButton.style.display = 'none';
    
    // 更新最高分
    if (score > gameStats.highestScore) {
        gameStats.highestScore = score;
    }
    
    // 更新游戏统计数据
    updateGameStats();
}

// 检查成就
function checkAchievements() {
    const now = new Date();
    const timeElapsed = (now - startTime) / 1000; // 秒
    
    // 首杀成就
    if (!achievements.first_kill.unlocked && foodEaten >= 1) {
        unlockAchievement('first_kill');
    }
    
    // 速度达人成就
    if (!achievements.speed_master.unlocked && score >= 1000) {
        unlockAchievement('speed_master');
    }
    
    // 马拉松选手成就
    if (!achievements.marathon.unlocked && snake.length >= 30) {
        unlockAchievement('marathon');
    }
    
    // 收藏家成就
    if (!achievements.collector.unlocked && gameStats.highestScore >= 5000) {
        unlockAchievement('collector');
    }
    
    // 简单大师成就
    if (!achievements.easy_achiever.unlocked && difficulty === 1 && score >= 500) {
        unlockAchievement('easy_achiever');
    }
    
    // 中等挑战者成就
    if (!achievements.medium_challenger.unlocked && difficulty === 2 && score >= 1000) {
        unlockAchievement('medium_challenger');
    }
    
    // 困难大师成就
    if (!achievements.hard_master.unlocked && difficulty === 3 && score >= 1500) {
        unlockAchievement('hard_master');
    }
    
    // 障碍专家成就
    if (!achievements.obstacle_expert.unlocked && difficulty === 3 && foodEaten >= 50) {
        unlockAchievement('obstacle_expert');
    }
    
    // 生存专家成就
    if (!achievements.survivor.unlocked && difficulty === 3 && timeElapsed >= 120) {
        unlockAchievement('survivor');
    }
}

// 解锁成就
function unlockAchievement(achievementKey) {
    if (achievements[achievementKey] && !achievements[achievementKey].unlocked) {
        achievements[achievementKey].unlocked = true;
        
        // 播放成就解锁音效
        if (achievementSound) achievementSound();
        
        // 显示成就解锁消息
        messageDisplay.textContent = `成就解锁: ${achievements[achievementKey].name}`;
        
        // 更新成就显示
        updateAchievementsDisplay();
        
        // 更新游戏统计数据
        updateGameStats();
    }
}

// 加载游戏统计数据
function loadGameStats() {
    try {
        const savedStats = localStorage.getItem('snakeGameStats');
        if (savedStats) {
            const parsedStats = JSON.parse(savedStats);
            gameStats = {...gameStats, ...parsedStats};
            
            // 合并成就数据
            if (parsedStats.achievements) {
                for (const [key, achievement] of Object.entries(parsedStats.achievements)) {
                    if (achievements[key]) {
                        achievements[key].unlocked = achievement.unlocked;
                    }
                }
            }
        }
    } catch (e) {
        console.log('Failed to load game stats from localStorage');
    }
}

// 更新游戏统计数据
function updateGameStats() {
    // 更新游戏统计数据
    gameStats.achievements = {};
    for (const [key, achievement] of Object.entries(achievements)) {
        gameStats.achievements[key] = { unlocked: achievement.unlocked };
    }
    
    // 保存到localStorage
    try {
        localStorage.setItem('snakeGameStats', JSON.stringify(gameStats));
    } catch (e) {
        console.log('Failed to save game stats to localStorage');
    }
    
    // 更新显示
    updateStatsDisplay();
}

// 更新统计数据显示
function updateStatsDisplay() {
    gamesPlayedDisplay.textContent = `游戏次数: ${gameStats.gamesPlayed}`;
    highestScoreDisplay.textContent = `最高分: ${gameStats.highestScore}`;
    
    // 更新成就显示
    updateAchievementsDisplay();
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);

// 为CanvasRenderingContext2D添加roundRect方法（如果不存在）
if (CanvasRenderingContext2D.prototype.roundRect === undefined) {
    CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius) {
        if (width < 2 * radius) radius = width / 2;
        if (height < 2 * radius) radius = height / 2;
        this.beginPath();
        this.moveTo(x + radius, y);
        this.arcTo(x + width, y, x + width, y + height, radius);
        this.arcTo(x + width, y + height, x, y + height, radius);
        this.arcTo(x, y + height, x, y, radius);
        this.arcTo(x, y, x + width, y, radius);
        this.closePath();
        return this;
    };
}

// 确保arcTo方法存在
if (CanvasRenderingContext2D.prototype.arcTo === undefined) {
    // 简单的矩形替代方案
    CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius) {
        this.beginPath();
        this.rect(x, y, width, height);
        this.closePath();
        return this;
    };
}